﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using Tin18.Resources;
using Tin18.Library;
using Newtonsoft.Json;
using Tin18.Model;
using Telerik.Windows.Controls;

namespace Tin18
{
    public partial class MainPage : PhoneApplicationPage
    {

        string TYPE = "number";
        string CATE = "-1";
        public MainPage()
        {
            InitializeComponent();
            Loaded += MainPage_Loaded;
            Unloaded += MainPage_Unloaded;
            List_DaLike.ItemsSource = App.DaLike;
            Layout_item.DataContext = new LoadingClass();
        }

        protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e)
        {
            if (MessageBox.Show("Bạn muốn thoát ứng dụng ?", "", MessageBoxButton.OKCancel) == MessageBoxResult.OK)
            {
                Application.Current.Terminate();
            }
            else
                e.Cancel = true;
            base.OnBackKeyPress(e);
        }

        void MainPage_Unloaded(object sender, RoutedEventArgs e)
        {
            InteractionEffectManager.AllowedTypes.Remove(typeof(RadDataBoundListBoxItem));
        }

        void MainPage_Loaded(object sender, RoutedEventArgs e)
        {
            GoogleAnalytics.EasyTracker.GetTracker().SendView("Main_Page");
            InteractionEffectManager.AllowedTypes.Add(typeof(RadDataBoundListBoxItem));
            while (NavigationService.CanGoBack)
            {
                NavigationService.RemoveBackEntry();
            }
            if (List_category.ItemsSource == null)
                LoadCategory();
            if (List_type.ItemsSource == null)
                LoadType();
        }

        public void LoadCategory()
        {
            Layout_item.DataContext = new LoadingClass();

            if (List_category.ItemsSource != null) return;
            string Param = MyLibrary.RanDomBase64() + MyLibrary.Base64(AppResources.GetCategory);
            WebClient webclientvideo = new WebClient();
            string URL = AppResources.Server + Param;
            webclientvideo.DownloadStringAsync(new Uri(URL));
            webclientvideo.DownloadStringCompleted += (ss, oo) =>
            {
                try
                {
                    string json = oo.Result;
                    if (!string.IsNullOrEmpty(json))
                    {
                        RootCategoryObject _Object = JsonConvert.DeserializeObject<RootCategoryObject>(json);
                        if (_Object.list.Count > 0)
                        {
                            List_category.ItemsSource = _Object.list;
                            if(List_type.ItemsSource !=null)
                                if (List_Tin18.ItemsSource == null)
                                {
                                    CATE = (List_category.SelectedItem as DataCategory).Id;
                                    TYPE = (List_type.SelectedItem as DataType).CategoryName;
                                    LoadHome(TYPE, CATE);
                                }
                        }
                    }

                }
                catch
                {
                    Layout_item.DataContext = new ErrorClass();
                };
            };
        }

        public void LoadType()
        {
            Layout_item.DataContext = new LoadingClass();
            if (List_type.ItemsSource != null) return;
            string Param = MyLibrary.RanDomBase64() + MyLibrary.Base64(AppResources.GetTypeAction);
            WebClient webclientvideo = new WebClient();
            string URL = AppResources.Server + Param;
            webclientvideo.DownloadStringAsync(new Uri(URL));
            webclientvideo.DownloadStringCompleted += (ss, oo) =>
            {
                try
                {
                    string json = oo.Result;
                    if (!string.IsNullOrEmpty(json))
                    {
                        RootTypeObject _Object = JsonConvert.DeserializeObject<RootTypeObject>(json);
                        if (_Object.list.Count > 0)
                        {
                            List_type.ItemsSource = _Object.list;
                            if(List_category.ItemsSource!=null)
                                if (List_Tin18.ItemsSource == null)
                                {
                                    CATE = (List_category.SelectedItem as DataCategory).Id;
                                    TYPE = (List_type.SelectedItem as DataType).CategoryName;
                                    LoadHome(TYPE, CATE);
                                }
                        }
                    }

                }
                catch
                {
                    Layout_item.DataContext = new ErrorClass();
                };
            };
        }

        ListNews listHome;
        public void LoadHome(string type, string cate)
        {
        
            listHome = new ListNews(type, cate,"");
            List_Tin18.DataContext = listHome;
            Layout_item.DataContext = listHome;
        }

        private void Reload_Click(object sender, RoutedEventArgs e)
        {
            switch (Main_panorama.SelectedIndex)
            {
                case 0:
                LoadCategory();
                LoadType();
                    break;
                case 1:
                     listTinSoc = new ListNews("number", "5","");
                        List_TinSoc.DataContext = listTinSoc;
                        Layout_item.DataContext = listTinSoc;
                    break;
                case 2:
                    if (TB_search.Text.Length > 0)
                    {
                        listSearch = new ListNews(HttpUtility.UrlEncode(TB_search.Text), "", "search");
                        List_Search.DataContext = listSearch;
                        Layout_item.DataContext = listSearch;
                    }
                    break;
                case 3: 
                    break;
                default: break;
            }

       
        }

        private void List_category_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (List_category == null || List_category.SelectedItem==null) return;
            CATE = (List_category.SelectedItem as DataCategory).Id;
            LoadHome(TYPE, CATE);
        }

        private void List_type_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (List_type == null || List_type.SelectedItem == null) return;
            TYPE = (List_type.SelectedItem as DataType).CategoryName;
            LoadHome(TYPE, CATE);
        }

        ListNews listTinSoc;
        private void Main_panorama_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            switch (Main_panorama.SelectedIndex)
            {
                case 0:
                    if(List_category.ItemsSource==null)
                        LoadCategory();
                    if(List_type.ItemsSource == null)
                        LoadType();
                    //if (List_Tin18.ItemsSource == null)
                    //{
                    //    CATE = (List_category.SelectedItem as DataCategory).Id;
                    //    TYPE = (List_type.SelectedItem as DataType).CategoryName;
                    //    LoadHome(TYPE, CATE);
                    //}
                    break;
                case 1:
                    if (List_TinSoc.ItemsSource == null)
                    {
                        listTinSoc = new ListNews("number", "5","");
                        List_TinSoc.DataContext = listTinSoc;
                        Layout_item.DataContext = listTinSoc;
                    }
                    break;
                case 2:
                    break;
                case 3:
                    break;
                default: break;
            }
        }

   

        private void List_TinSoc_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (List_TinSoc.SelectedItem == null) return;
            DataNews data = List_TinSoc.SelectedItem as DataNews;
            NavigationService.Navigate(new Uri("/ViewPage.xaml?ID=" + data.Id +
              "&cate=" + HttpUtility.UrlEncode(data.CategoryName) + "&time=" + HttpUtility.UrlEncode(data.Date) +
              "&title=" + HttpUtility.UrlEncode(data.Title) +
              "&description=" + HttpUtility.UrlEncode(data.ShortDescription) +
              "&thumb=" + HttpUtility.UrlEncode(data.Thumbnail) + "&view=" + data.View, UriKind.Relative));
            List_TinSoc.SelectedItem = null;
        }

        private void List_Tin18_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (List_Tin18.SelectedItem == null) return;
            DataNews data = List_Tin18.SelectedItem as DataNews;
            NavigationService.Navigate(new Uri("/ViewPage.xaml?ID=" + data.Id +
            "&cate=" + HttpUtility.UrlEncode(data.CategoryName) + "&time=" + HttpUtility.UrlEncode(data.Date) +
            "&title=" + HttpUtility.UrlEncode(data.Title) +
            "&description=" + HttpUtility.UrlEncode(data.ShortDescription) +
            "&thumb=" + HttpUtility.UrlEncode(data.Thumbnail) + "&view=" + data.View, UriKind.Relative));
            List_Tin18.SelectedItem = null;
            
        }

        private void List_DaLike_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (List_DaLike.SelectedItem == null) return;
            DataLike data = List_DaLike.SelectedItem as DataLike;
            NavigationService.Navigate(new Uri("/ViewPage.xaml?ID=" + data.Id +
            "&cate=" + HttpUtility.UrlEncode(data.CategoryName) + "&time=" + HttpUtility.UrlEncode(data.Date) +
            "&title=" + HttpUtility.UrlEncode(data.Title) +
            "&description=" + HttpUtility.UrlEncode(data.ShortDescription) +
            "&thumb=" + HttpUtility.UrlEncode(data.Thumbnail) + "&view=" + data.View, UriKind.Relative));
            List_DaLike.SelectedItem = null;
        }

        ListNews listSearch;
        private void btn_search_Click(object sender, RoutedEventArgs e)
        {
            if (TB_search.Text.Length > 0)
            {
                listSearch = new ListNews(HttpUtility.UrlEncode(TB_search.Text),"","search");
                List_Search.DataContext = listSearch;
                Layout_item.DataContext = listSearch;
            }
        }

        private void List_Search_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (List_Search.SelectedItem == null) return;
            DataNews data = List_Search.SelectedItem as DataNews;
            NavigationService.Navigate(new Uri("/ViewPage.xaml?ID=" + data.Id +
            "&cate=" + HttpUtility.UrlEncode(data.CategoryName) + "&time=" + HttpUtility.UrlEncode(data.Date) +
            "&title=" + HttpUtility.UrlEncode(data.Title) +
            "&description=" + HttpUtility.UrlEncode(data.ShortDescription) +
            "&thumb=" + HttpUtility.UrlEncode(data.Thumbnail) + "&view=" + data.View, UriKind.Relative));
            List_Search.SelectedItem = null;
        }

        private void TB_search_KeyDown(object sender, System.Windows.Input.KeyEventArgs e)
        {
            if (e.Key== System.Windows.Input.Key.Enter&& TB_search.Text.Length > 0)
            {
                listSearch = new ListNews(HttpUtility.UrlEncode(TB_search.Text), "", "search");
                List_Search.DataContext = listSearch;
                Layout_item.DataContext = listSearch;
                btn_search.Focus();
            }
        }
     
    }
    public class LoadingClass
    {
        public bool Error
        {
            get { return false; }
            set { }
        }
        public bool SysError
        {
            get { return false; }
            set { }
        }
        public bool Busy
        {
            get { return true; }
            set { }
        }
    }

    public class ErrorClass
    {
        public bool Error
        {
            get { return false; }
            set { }
        }
        public bool SysError
        {
            get { return true; }
            set { }
        }
        public bool Busy
        {
            get { return false; }
            set { }
        }
    }
   
}
